package com.hao.tool.util.module.file.controller;

import cn.hutool.core.io.FileUtil;
import com.hao.tool.common.constant.Commons;
import com.hao.tool.common.util.NetworkUtil;
import com.hao.tool.util.component.properties.PropertiesInfo;
import com.hao.tool.util.util.FileBlankUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 21:46
 */
@Controller
@RequestMapping("/file")
public class FileInfoController {

    private Logger logger = LoggerFactory.getLogger(FileInfoController.class);

    @Autowired
    private PropertiesInfo propertiesInfo;


    @GetMapping("/list")
    public ModelAndView list(String folder) {
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }


    @GetMapping("/add")
    public ModelAndView add() throws Exception {
        ModelAndView mv = new ModelAndView("fileinfo/add");
        return mv;
    }


    /**
     * 下载本地文件
     *
     * @param filePath    相对路径
     * @param absFilePath 绝对路径
     * @param response    响应
     * @param request     请求
     * @throws Exception
     */
    @GetMapping("/down")
    public void downInfo(String filePath, String absFilePath,
                         HttpServletResponse response, HttpServletRequest request) throws Exception {
        filePath = propertiesInfo.getLocalFileRootDir() + File.separator + filePath;
        File downFile = FileBlankUtil.buildAndFileIsExist(filePath, absFilePath);
        FileBlankUtil.fileSizeIsBig(downFile, Commons.SIZE_MB * 100);
        logger.info("IP地址为「{}」下载文件[{}]", NetworkUtil.getIpAddress(request), filePath);
        OutputStream outputStream = response.getOutputStream();
        byte[] bs = FileUtil.readBytes(downFile);
        response.setHeader("content-disposition", "attachment;fileName="
                + URLEncoder.encode(downFile.getName(), "UTF-8"));
        outputStream.write(bs);
        outputStream.close();
    }

}
